package com.bems.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.bems.dao.UserDao;
import com.bems.jdbc.common.QueryHelper;

import com.bems.pojo.User;
import com.bems.util.DigestMD;
import com.bems.util.PageUtil;

/**
 * 
 * @author 陈磊
 *
 */
public class UserSerive 
{
	
			/**
			 * 帐号和密码的校验
			 * @param account
			 * @param password
			 * @return 
			 */
			public User verify(String account,String password)
			{
				if(StringUtils.isNotEmpty(password)&&StringUtils.isNotEmpty(account))
				{
					User user = new User();
					Map<String, Object> map = new  HashMap<String, Object>();
					map.put("account", account);
					map.put("password", DigestMD.MD5(password));//MD5加密校验
					return user.get(map);
				}
				return null;

			}
			
			/**
			 *  添加用户
			 * @param user
			 * @return 成功返回ID 0：用户存在  null：插入失败 
			 */
			public Long save(User user)
			{
				if(StringUtils.isNotEmpty(user.getPassword()))
				{
					user.setPassword(DigestMD.MD5(user.getPassword()));//给密码做MD5摘要
				}
				return userDao.save(user);
			}
			
			/**
			 *  修改用户信息
			 * @param id 用户的id
			 * @param map 需要修改的表的属性和值
			 * @return
			 */
			public boolean update(Long id ,Map<String, Object> map)
			{
				if(id>0)
				{
					
					StringBuilder sql= new StringBuilder("UPDATE bems_user SET  ");
					 Set<String> sets = map.keySet();
					 int i = 0;
					  for (String string : sets) 
					  {
						  i++;
						 sql=sql.append(string+" =? ");
						 if (sets.size() > i) 
						 	{
							 sql.append(" , ");
						 	}
					  }
					 sql.append(" WHERE id = ?");	 
					 Object[] params = ArrayUtils.add(map.values().toArray(), id);
					 return QueryHelper.update(sql.toString(), params)==0?false:true;
				}
				return false;
				
			}
			
			/**
			 *   通过id删除用户 
			 * @param id
			 * @return
			 */
			public boolean delete(Long id)
			{
				User user = new User();
				return user.delete(id);
			}
			
			
			/**
			 * 按照分组取得用户
			 * @param group_id
			 * @return
			 */
			public List<User> getUsersByGroup(Long group_id)
			{
				return userDao.getUsers(group_id);
				
			}
			
			public PageUtil getUsersByGroup(Long group_id,int page,int size)
			{
			  PageUtil pageUtil = new PageUtil();	
				pageUtil.setPage(page);
				pageUtil.setSize(size);
				pageUtil.setList(userDao.getUsers(group_id, page, size));
				pageUtil.setTotalpage(new User().totalCount("group_id = "+group_id));//取得总数
			  
				return pageUtil;
				
			}
			
			
			UserDao userDao = new UserDao();
			
			public static void main(String[] args) 
			{
				UserSerive serive = new UserSerive();
				Map<String, Object> map = new  HashMap<String, Object>();
				map.put("account", "5");
				   System.out.println(serive.verify("admin", "bems"));
			}
}
